package com.qiyun.dinghuohui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyun.dinghuohui.activity.MainAdFaceActivity;
import com.qiyun.dinghuohui.base.BaseActivity;
import com.qiyun.dinghuohui.common.ApiName;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.common.Preferences;
import com.qiyun.dinghuohui.dialog.ServerSetDialog;
import com.qiyun.dinghuohui.http.HttpUtils;
import com.qiyun.dinghuohui.utils.AsyncJsonTask;
import com.qiyun.dinghuohui.utils.CommonUtil;
import com.qiyun.dinghuohui.utils.Constants;
import com.qiyun.dinghuohui.utils.GsonUtil;
import com.qiyun.dinghuohui.utils.Inject;
import com.qiyun.dinghuohui.utils.JsonBuilder;
import com.qiyun.dinghuohui.utils.JsonParamInfoReturn;
import com.qiyun.dinghuohui.utils.LogDebug;
import com.qiyun.dinghuohui.utils.PreferenceUtil;
import com.qiyun.dinghuohui.utils.ServerResponse;
import com.qiyun.dinghuohui.utils.SysUtil;
import com.qiyun.dinghuohui.vo.PublicSelectParamBean;
import com.qiyun.dinghuohui.vo.ServersBean;
import com.qiyun.dinghuohui.widget.notification.Configuration;
import com.qiyun.dinghuohui.widget.notification.Effects;
import com.qiyun.dinghuohui.widget.notification.NotificationView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2018\5\25 0025
 */

public class Login extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mBack;//退出
    @Inject(R.id.login_edit_account)
    private EditText mAccount;//账号
    @Inject(R.id.login_edit_password)
    private EditText mPassword;//密码
    @Inject(R.id.login_button)
    private TextView mTxtButton;//登录按钮
    @Inject(R.id.login_setup)
    private RelativeLayout mSeytup;//设置
    @Inject(R.id.login_visible_icon)
    private ImageView mVisibleIcon;//是否可见图标
    @Inject(R.id.rl_login_visible_icon)
    private RelativeLayout mRlVisibleIcon;
    @Inject(R.id.ll_version)
    private TextView mTextVersion;//版本号
    @Inject(R.id.checkbox)
    private CheckBox loginbyAd;

    private static boolean isVisible = false;
    private static final int OP_LOGIN_CHECKUPDATE_INITCONFIG = 1;
    private static final int OP_LOGIN_QUERY_BD = 2;
    private static final int OP_SYNC_DATA = 9999;//同步
    private final int Handel_Login = 5555;//登录

    private Handler mHandler;

    ApplicationDataHolder adh;
    private String m_username = "";
    private String m_password = "";
    private String m_userneedknow = "";
    private String sDeviceID = "";// 设备码，用于控制
    private String oldmacAddress = "";

    private static final int PERMISSON_SOTRAGE = 0;

    private void checkPermission() {
        if (checkStoragePermission(PERMISSON_SOTRAGE)) {
            permissionOk();
        }
    }


    private void permissionOk() {

    }
    @Override
    public void onStoragePermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToast("拒绝此权限，您将无法正常使用软件");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 5000);
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_login);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        mTextVersion.setText(getString(R.string.login_version) + CommonUtil.getVersionName(this));
    }

    @Override
    protected void onSetListener() {
        mVisibleIcon.setBackgroundResource(R.mipmap.login_unvisible);
        mPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        mTxtButton.setOnClickListener(this);
        mSeytup.setOnClickListener(this);
        mRlVisibleIcon.setOnClickListener(this);
        mBack.setOnClickListener(this);
    }

    // 与服务器失去联系的提示
    public void ShowTipNetExcept() {
        mHandler.sendEmptyMessage(Constants.SHOW_NETEXCEPT_TIPBYLOGIN);
    }

    private ServersBean serversBean;

    /**
     * 获取服务器器数据
     */
    private void getServersData() {
        HttpUtils.getInstance().url(ApiName.GET_SERVERS).executePost(new HttpUtils.HttpListener() {

            @Override
            public void onException(Throwable e) {
                super.onException(e);
                LogDebug.e(e);
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    serversBean = GsonUtil.GsonToBean(string, ServersBean.class);
                }
            }
        });
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        checkPermission();
        adh = (ApplicationDataHolder) getApplication();
        adh.setLogin(false);
        getServersData();
        ApplicationDataHolder.mLoginActivity = this;
        mHandler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case Constants.SHOW_LOADING:
                        AppDialogShow();
                        break;
                    case Constants.HIDE_LOADING:
                        AppDialogHide();
                        break;
                    case Constants.SHOW_NETEXCEPT_TIPBYLOGIN:
                        new AlertDialog.Builder(Login.this)
                                .setTitle("网络连接中断")
                                .setMessage("网络连接中断，请重新登录，如重新登录不成功，请联系现场工作人员。")
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        adh.bNetExceptShowTip = false;
                                    }
                                }).show();
                        break;
                    case Handel_Login:
                        if (m_username.equals("") || m_password.equals("")) {
                            showToast("请您输入用户名和密码");
                        } else {
                            mHandler.sendEmptyMessage(Constants.SHOW_LOADING);
                            JSONObject postData = null;
                            try {
                                JsonBuilder jb = new JsonBuilder();
                                //判断是否是总代理登录
                                if (loginbyAd.isChecked()) {
                                    jb.setUt(1);// AD Login
                                } else {
                                    jb.setUt(0);
                                }
                                postData = jb.setUsername(m_username)
                                        .setPassword(m_password)
                                        .setDeviceId(adh.getDeviceId())
                                        .setDeviceId(adh.getWifiMacAddress())
                                        .setOp(OP_LOGIN_CHECKUPDATE_INITCONFIG)
                                        .buildJson();
                                new AsyncJsonTask(adh.getServerUrl(true, 0, "B"), ApiName.LOGIN, Login.this).execute(postData);
                            } catch (Exception e) {
                                e.printStackTrace();
                                mHandler.sendEmptyMessage(Constants.HIDE_LOADING);
                            }
                        }
                        break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_login_visible_icon:
                //是否可见
                m_password = mPassword.getText().toString();
                if (!isVisible) {
                    isVisible = true;
                    setImageWH(mVisibleIcon, 22, 15);
                    mVisibleIcon.setBackgroundResource(R.mipmap.login_visible);
                    //设置密码可见
                    mPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    isVisible = false;
                    setImageWH(mVisibleIcon, 22, 22);
                    mVisibleIcon.setBackgroundResource(R.mipmap.login_unvisible);
                    //不可见
                    mPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }
                if (!CommonUtil.isEmpty(m_password)) {
                    mPassword.setSelection(m_password.length());
                }
                break;
            case R.id.login_button:
                //开始登录
                loginButtonClick();
                break;
            case R.id.login_setup:
                //点击设置
                showServerDialog();
                break;
            case R.id.back:
                afterBackPressed();
                break;
        }
    }


    /**
     * 提示登录信息错误
     */
    private void showLoginError() {

        NotificationView.build(this, getString(R.string.login_error_note), Effects.standard, R.id.notify_location,
                new Configuration.Builder()
                        .setBackgroundColor(Color.parseColor("#FF7170"))
                        .setTextColor(Color.parseColor("#FFFFFF"))
                        .setViewHeight(24).build())
                .show();
    }

    /**
     * 开始登录
     */
    private void sendLogin() {
        // 判断有无数据需要同步
        adh.setLogin(false);
        m_username = mAccount.getText().toString();
        m_password = mPassword.getText().toString();
        if (m_username.equals("") || m_password.equals("")) {
            showToast("请您输入用户名和密码");
        } else {
            mHandler.sendEmptyMessage(Handel_Login);
        }
    }

    /**
     * 点击登录按钮,判断是否同步数据
     */
    public void loginButtonClick() {
        String url = (String) PreferenceUtil.getParam(Preferences.SERVER_URL,
                ClientCookie.getServerUrl());
        adh.setServerUrl(url);
        if ("".equals(url)) {
            showToast("请您先设置Server的路径");
        } else {
            ClientCookie.setServerUrl(url);
            // 先要进行更新判断 判断有无数据同步
            m_username = mAccount.getText().toString();
            m_password = mPassword.getText().toString();
            if (!checkDataNeedSync(getThis(), adh, mHandler, OP_SYNC_DATA, true, true)) {
                sendLogin();
            }
        }
    }

    private ServerSetDialog mServerDialog;

    /**
     * 显示设置服务器弹窗
     */
    private void showServerDialog() {

        if (mServerDialog == null) {
            mServerDialog = new ServerSetDialog(getThis());
        }
        mServerDialog.setCancelable(false);
        mServerDialog.setListener(new ServerSetDialog.Listener() {
            @Override
            public void onConfirm(String server, final String name, final String code, boolean isChoose) {
                super.onConfirm(server, name, code, isChoose);
                String ip = (String) PreferenceUtil.getParam(Preferences.SERVER_URL, "");
                final String name1 = (String) PreferenceUtil.getParam(Preferences.COMPANY_NAME, "");
                final String code1 = (String) PreferenceUtil.getParam(Preferences.COMPANY_CODE, "");
                List<String> servers = new ArrayList<String>();
                final List<String> names = new ArrayList<String>();
                for (ServersBean.ListBean bean : serversBean.getList()) {
                    servers.add(bean.getIp());
                    names.add(bean.getName());
                }
                if (isChoose) {
                    if (servers.contains(server)) {
                        PreferenceUtil.setParam(Preferences.SERVER_URL, "http://" + String.valueOf(server));
                        if (!server.equals(ip)) {
                            showToast("设置IP成功");
                        }
                        mServerDialog.dismiss();
                    } else {
                        showToast("请选择正确的IP");
                    }
                    if (names.contains(name)) {
                        PreferenceUtil.setParam(Preferences.COMPANY_NAME, String.valueOf(name));
                        if (!name.equals(name1)) {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("设置公司名称成功");
                                }
                            }, 1200);
                        }
                        mServerDialog.dismiss();
                    } else {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                showToast("请选择正确的公司名称");
                            }
                        }, 1200);
                    }
                } else {
                    if (!CommonUtil.isEmpty(code)) {
                        PreferenceUtil.setParam(Preferences.COMPANY_CODE, String.valueOf(code));
                        if (!code.equals(code1)) {
                            showToast("设置公司代码成功");
                        }
                        mServerDialog.dismiss();
                    } else {
                        PreferenceUtil.setParam(Preferences.COMPANY_CODE, "");
                        mServerDialog.dismiss();
                    }
                    if (names.contains(name)) {
                        PreferenceUtil.setParam(Preferences.COMPANY_NAME, String.valueOf(name));
                        if (!name.equals(name1)) {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("设置公司名称成功");
                                }
                            }, 1200);
                        }
                        mServerDialog.dismiss();
                    } else {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                showToast("请选择正确的公司名称");
                            }
                        }, 1200);
                    }
                }
            }
        });
        mServerDialog.show();
        mServerDialog.setServerData(serversBean);
    }

    /**
     * 设置ImageView宽高
     *
     * @param mImageView
     */
    private void setImageWH(ImageView mImageView, float width, float height) {
        //设置图片参数
        ViewGroup.LayoutParams layoutParams = mImageView.getLayoutParams();
        layoutParams.width = CommonUtil.dip2px(width, this);
        layoutParams.height = CommonUtil.dip2px(height, this);
        mImageView.setLayoutParams(layoutParams);
    }

    @Override
    public void onPostDataStart() {
        mHandler.sendEmptyMessage(Constants.SHOW_LOADING);
    }

    @Override
    public void onPostDataSuccess(ServerResponse response) {
        try {
            JsonParamInfoReturn jsonParamInfoReturn = ApplicationDataHolder.paramCheckByReturn(response);
            if (!jsonParamInfoReturn.isParam_aliay()) {
                showToast(ApplicationDataHolder.responseCallFileTip);
                return;
            }
            switch (CommonDataSets.getIntforString(jsonParamInfoReturn.getParam_op())) {
                case OP_SYNC_DATA:// 数据同步返回
                    if (jsonParamInfoReturn.isParam_aliay()) {
                        adh.setSync_windowstime_begin(jsonParamInfoReturn.getCommunicationsWindowClientBegin());
                        adh.setSync_windowstime_end(jsonParamInfoReturn.getCommunicationsWindowClientEnd());
                        CommonDataSets.userDataClearSync(adh.getUsername(), true);// 同步完成后，更改标记
                        CommonDataSets.saveUserDataToDisk();
                        showToast("数据同步完成,请您登录");
                        mHandler.sendEmptyMessage(Handel_Login);
                    } else {
                        showToast("数据同步失败,请重试");
                    }
                    break;
                case OP_LOGIN_QUERY_BD:// 绑定
                    String s_bduser = jsonParamInfoReturn.getParam_json().getString("bduser");
                    if (s_bduser == null) {
                        s_bduser = "";
                    }
                    s_bduser = s_bduser.trim();
                    String s_bdusername = jsonParamInfoReturn.getParam_json().getString("bdusername");
                    if (s_bdusername == null) {
                        s_bdusername = "";
                    }
                    s_bdusername = s_bdusername.trim();
                    if (!"".equals(s_bdusername)) {
//                        loginTxtBdInfo.setText("尊敬的" + s_bdusername + ",请输入密码登录");
//                        mUsername.setText(s_bduser);
//                        loginTxtBdInfo.setVisibility(View.VISIBLE);
//                        loginTableRowAccount.setVisibility(View.GONE);
//                        loginbyAd.setVisibility(View.GONE);
                    } else {
//                        loginTxtBdInfo.setVisibility(View.GONE);
//                        loginTableRowAccount.setVisibility(View.VISIBLE);
//                        loginbyAd.setVisibility(View.VISIBLE);
                    }
                    break;
                case OP_LOGIN_CHECKUPDATE_INITCONFIG:// 登录直接取回数据，减少
                    // 判断是否在通信窗口
//                 if (DateUtil.compareDates(jsonParamInfoReturn.
//				   getCommunicationsWindowClientBegin(), new Date())!=1 &&
//				   DateUtil.compareDates(jsonParamInfoReturn.
//				   getCommunicationsWindowClientEnd(), new Date())!=-1 ){
//				    //在通信窗口时间范围 }else{
//				 }
                    String configname = jsonParamInfoReturn.getParam_json().getString("1configname");
                    if (configname == null) {
                        configname = "";
                    }
                    String configvalue = jsonParamInfoReturn.getParam_json().getString("1configvalue");
                    if (configvalue == null) {
                        configvalue = "";
                    }
                    String sTemp = jsonParamInfoReturn.getParam_json().getString("1configinfo1");
                    if (sTemp == null) {
                        sTemp = "";
                    }
                    final String configinfo1 = sTemp;
                    String configmemo = jsonParamInfoReturn.getParam_json().getString("1configmemo");
                    if (configmemo == null) {
                        configmemo = "";
                    }
                    final String needknow = jsonParamInfoReturn.getParam_json().getString("needknow");
                    m_userneedknow = jsonParamInfoReturn.getParam_json().getString("userneedknow");
                    if (m_userneedknow == null) {
                        m_userneedknow = "";
                    }
                    adh.setSc_Brand_Tip(jsonParamInfoReturn.getParam_json().getString("2configinfo1"));
                    adh.setSc_Brand_PassWord(jsonParamInfoReturn.getParam_json().getString("2configvalue"));
                    adh.setSc_Brand_Memo(jsonParamInfoReturn.getParam_json().getString("2configmemo"));
                    adh.setSc_Brand_PicShowCount(jsonParamInfoReturn.getParam_json().getInt("4configvalue"));
                /*
                 * 暂时屏蔽，在后台管理转化
				 * adh.setSc_Pic_Modal(result.getString("3configvalue"));
				 * Log.d("TAG", "setSc_Pic_Modal()->"+adh.getSc_Pic_Modal());
				 */
                    adh.setPic_Mode(jsonParamInfoReturn.getParam_json().getInt("3configvalue"));
                    final boolean ok = jsonParamInfoReturn.getParam_json().getBoolean("logon");
                    adh.setLogin(ok);
                    if (!configvalue.trim().toUpperCase().equals(adh.VERSIONFORAUTO.toUpperCase())) {
                        //删除已存在的apk
                        File dir = new File(CommonDataSets.CLIENT_STRONGPATH + "/");
                        if (dir.exists()) {
                            File[] files = dir.listFiles();
                            for (File file : files) {
                                if (file.getName().contains(".apk")) {
                                    try {
                                        CommonUtil.deleteFile(file);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        // 提示更新
                        new AlertDialog.Builder(Login.this)
                                .setTitle("提示")
                                .setMessage(configmemo)
                                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (configinfo1.toUpperCase().subSequence(0, 4).equals("HTTP")) {
                                            downFile(configinfo1, ClientCookie.APP_NAME + ".apk");
                                        } else {
                                            downFile(adh.getServerUrl(true, 0, "B") + configinfo1, ClientCookie.APP_NAME + ".apk");
                                        }
                                    }
                                }).show();

                    } else {// 不需要更新
                        if (ok) {
                            adh.setSync_windowstime_begin(jsonParamInfoReturn.getCommunicationsWindowClientBegin());
                            adh.setSync_windowstime_end(jsonParamInfoReturn.getCommunicationsWindowClientEnd());
                            String username = "";
                            try {
                                username = jsonParamInfoReturn.getParam_un();
                                adh.setUsername(username);
                                adh.setPassword(m_password);
                                adh.setUserType(jsonParamInfoReturn.getParam_ut());
                                // 这里暂时这样处理，总代用户，分析使用实时的，如是总代，则登录状态设置成未登录，以便后台不进行WIFI开关
                                adh.setLogin(true);
                                adh.setCanReadRefrushBackData(true);
                                adh.setRegionStr(jsonParamInfoReturn.getParam_json().getString("regionStr"));
                                adh.setUserGroup(jsonParamInfoReturn.getParam_json().getString("usergroup"));

                                adh.REPORT_WCL = jsonParamInfoReturn.getParam_json().getString("rwcl").equals("1");
                                adh.REPORT_SEASON = jsonParamInfoReturn.getParam_json().getString("rseason").equals("1");
                                adh.REPORT_SERIAL = jsonParamInfoReturn.getParam_json().getString("rserial").equals("1");
                                adh.REPORT_WAVE = jsonParamInfoReturn.getParam_json().getString("rwave").equals("1");
                                adh.REPORT_TYPE = jsonParamInfoReturn.getParam_json().getString("rtype").equals("1");
                                adh.REPORT_STYLE = jsonParamInfoReturn.getParam_json().getString("rstyle").equals("1");
                                adh.REPORT_COLOR = jsonParamInfoReturn.getParam_json().getString("rcolor").equals("1");
                                adh.REPORT_SIZE = jsonParamInfoReturn.getParam_json().getString("rsize").equals("1");
                                adh.REPORT_PRICE = jsonParamInfoReturn.getParam_json().getString("rprice").equals("1");
                                adh.REPORT_GOODSLEVEL = jsonParamInfoReturn.getParam_json().getString("rgl").equals("1");
                                adh.REPORT_BANDS = jsonParamInfoReturn.getParam_json().getString("rbands").equals("1");
                                adh.REPORT_BANDSGL = jsonParamInfoReturn.getParam_json().getString("rbandsgl").equals("1");
                                adh.AD_SHOWALLCOUNT = jsonParamInfoReturn.getParam_json().getString("showcount").equals("1");
                                adh.AD_SHOWALLAMOUNT = jsonParamInfoReturn.getParam_json().getString("showamount").equals("1");
                                adh.OrderInputConfigModify = jsonParamInfoReturn.getParam_json().getInt("rinmod") == 1;

                                CommonDataSets.ds_config_activity.orderShowConfigSync = false;
                                CommonDataSets.ds_config_activity.orderShowAccount = adh.getUsername();

                                CommonDataSets.ds_config_activity.orderShowPic = jsonParamInfoReturn
                                        .getParam_json().getInt("ospic") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Season = jsonParamInfoReturn
                                        .getParam_json().getInt("osseason") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Serial = jsonParamInfoReturn
                                        .getParam_json().getInt("osserial") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Wave = jsonParamInfoReturn
                                        .getParam_json().getInt("oswave") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Type = jsonParamInfoReturn
                                        .getParam_json().getInt("ostype") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Style = jsonParamInfoReturn
                                        .getParam_json().getInt("osstyle") == 1;
                                CommonDataSets.ds_config_activity.orderShow_StylePos = jsonParamInfoReturn
                                        .getParam_json().getInt("osstylepos") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Price = jsonParamInfoReturn
                                        .getParam_json().getInt("osprice") == 1;
                                CommonDataSets.ds_config_activity.orderShow_Color = jsonParamInfoReturn
                                        .getParam_json().getInt("oscolor") == 1;
                                //保存登录信息
                                CommonDataSets.saveToCacheUserData(jsonParamInfoReturn.getParam_json(), true);

                                JSONObject objBoardInfo = jsonParamInfoReturn.getParam_json().getJSONObject("boardInfo");
                                CommonDataSets.ds_quyu_kehu.clear();
                                CommonDataSets.populateObject(jsonParamInfoReturn.getParam_json().getJSONArray("shops"),
                                        CommonDataSets.ds_quyu_kehu);

                                adh.setSc_Wifiid(objBoardInfo.getInt("wifiid"));
                                adh.setBoardInfo_name(objBoardInfo.getString("name"));//账号name
                                adh.setUserRegion(objBoardInfo.getString("region"));//公司类型
                                try {
                                    adh.setMemo(jsonParamInfoReturn.getParam_json().getString("memo").split(","));
                                } catch (Exception e) {
                                    adh.setMemo(null);
                                }
                                if (!loginbyAd.isChecked()) {
                                    String allowBrand = "全部";
                                    try {
                                        allowBrand = objBoardInfo.getString("ALLOWBRAND");

                                        adh.setPlanamount(objBoardInfo.getInt("pa"));// 针对完成率新增加的参数
                                        adh.setPlancount(objBoardInfo.getInt("pc"));
                                        adh.setPlanstyle(objBoardInfo.getInt("ps"));

                                        adh.planmustcount = objBoardInfo.getInt("mm");
                                        adh.planmuststyle = objBoardInfo.getInt("pms");
                                        adh.ordercommit = objBoardInfo.getInt("ost") == 1;
                                        adh.orderCommitAmount = objBoardInfo.getInt("oa");
                                        adh.orderCommitCount = objBoardInfo.getInt("oc");
                                        adh.orderCommitStyle = objBoardInfo.getInt("os");
                                        adh.orderCommitMustStyle = objBoardInfo.getInt("mc");
                                        adh.orderCommitMustCount = objBoardInfo.getInt("ms");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    adh.setBoardInfo_allowBrand(allowBrand);
                                    CommonDataSets.ALLOWBRAND = allowBrand; // 设置允许显示的品牌
                                }
                                adh.setBoardInfo_budget(objBoardInfo.getString("budget"));
                                adh.setBoardInfo_comments(objBoardInfo.getString("comments"));
                                adh.setBoardInfo_groupname(objBoardInfo.getString("groupname"));
                                adh.setLevel(objBoardInfo.getString("level"));
                                adh.setSizemaxcount(objBoardInfo.getInt("maxcount"));
                                adh.setAccount_jhjlb(objBoardInfo.getInt("jhjlb"));
                                adh.setAccountRegionBig(jsonParamInfoReturn.getParam_json().getString("regionbig"));
                                adh.setAccountRegion(jsonParamInfoReturn.getParam_json().getString("region"));

                                // 判断网络设备ID
                                oldmacAddress = jsonParamInfoReturn.getParam_json().getString("oldmac");
                                if (oldmacAddress == null) {
                                    oldmacAddress = "";
                                }
                                gotoFaceNeedknow(needknow);
                            } catch (JSONException e) {
                                showToast("json解析异常");
                                e.printStackTrace();
                            }
                        } else {
                            if (jsonParamInfoReturn.getParam_message().equals("")) {
                                showToast("登录失败，请重试");
                            } else {
                                showLoginError();
                            }
                        }
                    }
                    break;
            }
        } catch (JSONException e) {
            showToast("登录失败，请重试");
            e.printStackTrace();
        }
    }

    private void gotoFaceNeedknow(String needknow) {
        // 订货须知 needknow
        if (needknow.trim().equals("")) {
            if (adh.isCanReadRefrushBackData()) {
                showLoading("数据下载中...");
                adh.downloadBaseFileByServer();
                //全部数据下载完成后跳转
            }
        } else {
            // 订货须知
            new AlertDialog.Builder(Login.this)
                    .setTitle("请认真阅读订货须知")
                    .setMessage(needknow)
                    .setPositiveButton("接受订货须知",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (adh.isCanReadRefrushBackData()) {
                                        showLoading("数据下载中...");
                                        adh.downloadBaseFileByServer();
                                        //全部数据下载完成后跳转
                                    }
                                }
                            })
                    .setNegativeButton("不接受", null).show();
        }
    }

    //跳转主界面
    public void gotoFace() {
        dismissLoading();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPassword.setText("");
            }
        });
        //下载新的数据
        if (!"".equals(oldmacAddress)
                && !oldmacAddress.equals(adh.getWifiMacAddress())
                && CommonDataSets.ds_config_activity.clientcheck) {
            // 提示强制登录
            new AlertDialog.Builder(Login.this)
                    .setTitle("强行登录")
                    .setMessage("您上次登录设备与本次不一致，请确认")
                    .setPositiveButton("确认，强行登录",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    gotoFace_Go();
                                }
                            }).show();
        } else {
            // 正常登录
            gotoFace_Go();
        }
    }

    /**
     * 判断是否是AD,进入主界面或AD界面
     */
    private void gotoFace_Go() {
        if (!"".equals(m_userneedknow)) {
            // 显示用户的订货须知
        }
        Log.d("", "adh.getUserType()->" + adh.getUserType());
        if (adh.getUserType() == 0) {
            showMainface();
        } else if (adh.getUserType() == 1) {
            // 进入AD控制
            ShowAdFace();
        }
    }

    /**
     * 进入首页
     */
    private void showMainface() {
        // 启动WIFI开关,客户端登陆后，自动断开wifi
        // 如果是总代,也不需要关闭wifi
        adh.checkSaveOrderRealTime();
        if (!adh.getLevel().toUpperCase().equals("A")) {
            if (CommonDataSets.ds_config_activity.netOpen) {
                adh.wifiSaveNetId();
                adh.getWifiAdminClose();
            }
        }
        adh.saveOrderFlagEnabled(false);
        mHandler.sendEmptyMessage(Constants.HIDE_LOADING);
        Intent i = new Intent();
        i.setClass(Login.this, MainActivity.class);
        startActivity(i);
        finish();
    }

    /**
     * 进入AD界面
     */
    private void ShowAdFace() {
        adh.checkSaveOrderRealTime();
        mHandler.sendEmptyMessage(Constants.HIDE_LOADING);
        Intent i = new Intent();
        i.setClass(Login.this, MainAdFaceActivity.class);// MainByAdActivity.class
        startActivity(i);
    }

    @Override
    public void onPostDataError(ServerResponse response) {
        showToast(String.valueOf(response.message));
    }

    @Override
    public void onPostDataComplete(ServerResponse response) {
        mHandler.sendEmptyMessage(Constants.HIDE_LOADING);
    }

    @Override
    public void setProgressMessage(String message) {

    }

    @Override
    public void publicSelectCallBack(PublicSelectParamBean pspb) {

    }

    /**
     * 下载更新应用
     *
     * @param url
     * @param apkname
     */
    void downFile(final String url, final String apkname) {
        mHandler.sendEmptyMessage(Constants.SHOW_LOADING);
        HttpUtils.getInstance().loadFile(url, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                LogDebug.e(e);
            }

            @Override
            public void onResponseProgress(long progress, long total, boolean done) {
                float per = (float) progress / (float) total * (float) 100;
                String pers = String.valueOf(per);
                if (pers.length() > 5) {
                    pers = pers.substring(0, 5);
                }
                final String finalPers = pers;
                showDownProgress("正在下载" + " " + finalPers + "%");
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                showDownProgress("准备安装，请稍后");
                String savepath = CommonDataSets.CLIENT_STRONGPATH + "/" + apkname;
                final File file = new File(savepath);
                try {
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    dismissDownProgress();
                    SysUtil.installApk(getThis(), file.getPath());
                } catch (Exception e) {
                    LogDebug.e(e);
                }
            }
        });
    }
}
